package com.jjc.android;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.jjc.android.util.MediaLoader;
import com.jjc.android.util.MultiLanguageUtil;
import com.lxj.xpopup.XPopup;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.tencent.bugly.crashreport.CrashReport;
import com.jjc.android.util.GlobalActivityStack;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import io.github.inflationx.calligraphy3.CalligraphyConfig;
import io.github.inflationx.calligraphy3.CalligraphyInterceptor;
import io.github.inflationx.viewpump.ViewPump;
import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;
import okhttp3.OkHttpClient;
import xyz.doikki.videoplayer.exo.ExoMediaPlayerFactory;
import xyz.doikki.videoplayer.player.VideoViewConfig;
import xyz.doikki.videoplayer.player.VideoViewManager;

public class App extends MultiDexApplication {

  private static App applictionContext;

  public static App getContext(){
    return applictionContext;
  }

  private OkHttpClient okHttpClient;

  public OkHttpClient getOkHttpClient(){
    return okHttpClient;
  }


  public static final long DEFAULT_MILLISECONDS = 6000000;
  @Override
  public void onCreate() {
    super.onCreate();
    applictionContext = this;
    CrashReport.initCrashReport(this, "617fee8c29", false);
    initCalligraphy();
    GlobalActivityStack.registerCallback(this,null);
    ToastUtils.init(this);

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
    loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
    loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
    builder.addInterceptor(loggingInterceptor);
    builder.readTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
    builder.writeTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
    builder.connectTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间
    HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
    builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
    okHttpClient = builder.build();
    OkGo.getInstance().setOkHttpClient(okHttpClient).init(this);
    XPopup.setShadowBgColor(Color.parseColor("#33000000"));
    RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
      @Override
      public void accept(Throwable throwable) throws Exception {
        Log.e("RxJavaPlugins", throwable.getMessage());
      }
    });

    Album.initialize(AlbumConfig.newBuilder(this)
            .setAlbumLoader(new MediaLoader())
            .build());

    VideoViewManager.setConfig(VideoViewConfig.newBuilder()
            .setLogEnabled(BuildConfig.DEBUG) //调试的时候请打开日志，方便排错
            .setPlayerFactory(ExoMediaPlayerFactory.create())
            .build());

    initCalligraphy();

    MultiLanguageUtil.init(this);
  }

  @Override
  protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
  }

  private void initCalligraphy(){
    ViewPump.init(ViewPump.builder()
            .addInterceptor(new CalligraphyInterceptor(
                    new CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/DingTalk_Sans.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()))
            .build());
  }

  static {
    SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> new ClassicsHeader(context));
    SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> new ClassicsFooter(context));
  }

  public static String getFileAuthorities(){
    return App.getContext().getPackageName() + ".album.provider";
  }

  @Override
  public void onConfigurationChanged(@NonNull Configuration newConfig) {
    ContextWrapper wrapper = MultiLanguageUtil.getInstance().wrap(this);
    super.onConfigurationChanged(wrapper.getApplicationContext().getResources().getConfiguration());
  }
  @Override
  public Resources getResources() {
    Resources res = super.getResources();
    try {
      if(MultiLanguageUtil.getInstance()!=null){
        Locale locale = res.getConfiguration().getLocales().get(0);
        if(!locale.getDisplayLanguage().equals(MultiLanguageUtil.getInstance().getLanguageLocale().getDisplayLanguage())){
          MultiLanguageUtil.getInstance().updateLocal(this,res);
        }
      }
    }catch (Exception e){

    }
    return res;
  }

}
